package push_config

import (
	"context"
	"git.mycaigou.com/gfyx/common/tenant_db"
	"gorm.io/gorm"
	"time"
)

type GfyxSubscriptionPushConfigRepos struct {
	tenant_db.TenantDB
}

func NewSubscriptionPushConfigRepos() GfyxSubscriptionPushConfigReposIface {
	return &GfyxSubscriptionPushConfigRepos{}
}

func (g *GfyxSubscriptionPushConfigRepos) AddSubscriptionPushConfig(ctx context.Context, data *GfyxSubscriptionPushConfig) error {
	data.CreatedOn = time.Now()
	data.ModifiedOn = time.Now()
	err := g.GetTenantDB(ctx).Create(data).Error
	if err != nil {
		return err
	}
	return nil
}

func (g *GfyxSubscriptionPushConfigRepos) SaveSubscriptionPushConfig(ctx context.Context, data *GfyxSubscriptionPushConfig) error {
	data.CreatedOn = time.Now()
	data.ModifiedOn = time.Now()
	err := g.GetTenantDB(ctx).Save(data).Error
	if err != nil {
		return err
	}
	return nil
}

func (g *GfyxSubscriptionPushConfigRepos) GetSubscriptionPushConfigByUser(ctx context.Context, userGUID string) (*GfyxSubscriptionPushConfig, error) {
	subscriptionPushConfig := &GfyxSubscriptionPushConfig{}
	err := g.GetTenantDB(ctx).
		Where("user_guid = ?", userGUID).
		Order("created_on desc").First(subscriptionPushConfig).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return subscriptionPushConfig, err
	}
	return subscriptionPushConfig, nil
}
